{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "13f48c20",
   "metadata": {},
   "source": [
    "* 记录人：LZ\n",
    "* 时间：2022-5-10\n",
    "* week10: 语音系统API——语音识别/语音合成\n",
    "* 学习资源：[语音识别](https://github.com/Baidu-AIP/speech-demo/tree/master/rest-api-asr/python)    \n",
    "[短语音识别——百度开放平台](https://ai.baidu.com/ai-doc/SPEECH/Vk38lxily)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d5a180d",
   "metadata": {},
   "source": [
    "# 知识点  \n",
    "\n",
    "1. 语音识别：speech_recognition  \n",
    "2. 自动语音识别（ASR）：电脑自动将人类语音转换为文字  \n",
    "3. 语音合成（TTS）：电脑将文字/文本转换为语音\n",
    "\n",
    "\n",
    "## 1.语音识别  \n",
    "---\n",
    "* 参考百度API开放平台：https://ai.baidu.com/ai-doc/SPEECH/Vk38lxily\n",
    "* 代码来源于：https://github.com/Baidu-AIP/speech-demo/blob/master/rest-api-asr/python/asr_raw.py  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "42cc3eb1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"refresh_token\":\"25.8980f71bba9e2ccbb6647e9c14c4a337.315360000.1967512461.282335-26194923\",\"expires_in\":2592000,\"session_key\":\"9mzdAvJHhszT\\/\\/mzEubEEo9ZGJq2zJ8Yxtl1C94meVckuqln4fxaJ2g8iUMMTemR37lAspszETvrcmuiotmjvHCTGgpjPQ==\",\"access_token\":\"24.90f56999e2e4c8d9cfbdd6efb440de32.2592000.1654744461.282335-26194923\",\"scope\":\"audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx\",\"session_secret\":\"f3172b3bad1aed7792cdf5400fac05d3\"}\n",
      "\n",
      "{'refresh_token': '25.8980f71bba9e2ccbb6647e9c14c4a337.315360000.1967512461.282335-26194923', 'expires_in': 2592000, 'session_key': '9mzdAvJHhszT//mzEubEEo9ZGJq2zJ8Yxtl1C94meVckuqln4fxaJ2g8iUMMTemR37lAspszETvrcmuiotmjvHCTGgpjPQ==', 'access_token': '24.90f56999e2e4c8d9cfbdd6efb440de32.2592000.1654744461.282335-26194923', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': 'f3172b3bad1aed7792cdf5400fac05d3'}\n",
      "SUCCESS WITH TOKEN: 24.90f56999e2e4c8d9cfbdd6efb440de32.2592000.1654744461.282335-26194923 ; EXPIRES IN SECONDS: 2592000\n",
      "url is http://vop.baidu.com/server_api?cuid=123456PYTHON&token=24.90f56999e2e4c8d9cfbdd6efb440de32.2592000.1654744461.282335-26194923&dev_pid=1537\n",
      "header is {'Content-Type': 'audio/pcm; rate=16000', 'Content-Length': 129600}\n",
      "Request time cost 0.909526\n",
      "{\"corpus_no\":\"7095940793659866072\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"北京科技馆。\"],\"sn\":\"231355298091652152461\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "API_KEY = '7vVrQGv694z3sSwpGGAPdQSk'\n",
    "SECRET_KEY = '2061LwY18Wq1pIObgqBE8qRwT9NtxUmT'\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = './audio/16k.pcm'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "#测试自训练平台需要打开以下信息， 自训练平台模型上线后，您会看见 第二步：“”获取专属模型参数pid:8001，modelid:1234”，按照这个信息获取 dev_pid=8001，lm_id=1234\n",
    "# DEV_PID = 8001 ;   \n",
    "# LM_ID = 1234 ;\n",
    "\n",
    "# 极速版 打开注释的话请填写自己申请的appkey appSecret ，并在网页中开通极速版（开通后可能会收费）\n",
    "\n",
    "#DEV_PID = 80001\n",
    "#ASR_URL = 'http://vop.baidu.com/pro_api'\n",
    "#SCOPE = 'brain_enhanced_asr'  # 有此scope表示有asr能力，没有请在网页里开通极速版\n",
    "\n",
    "# 忽略scope检查，非常旧的应用可能没有\n",
    "# SCOPE = False\n",
    "\n",
    "\n",
    "# 极速版\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "\n",
    "    \"\"\"\n",
    "    httpHandler = urllib2.HTTPHandler(debuglevel=1)\n",
    "    opener = urllib2.build_opener(httpHandler)\n",
    "    urllib2.install_opener(opener)\n",
    "    \"\"\"\n",
    "\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    #测试自训练平台需要打开以下信息\n",
    "    #params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "    params_query = urlencode(params);\n",
    "\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = ASR_URL + \"?\" + params_query\n",
    "    print(\"url is\", url);\n",
    "    print(\"header is\", headers)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "    print(result_str)\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1745b45",
   "metadata": {},
   "source": [
    "## 2.真对话机器人（文本回复）\n",
    "* 1.识别语音--> 转换百度语音识别指定格式文件  \n",
    "* 2.调用百度ASR接口，转换成文本  \n",
    "* 3. 回复？数据结构：字典{key:value}, key(人) 作为输入input， value(机器) 作为output  \n",
    "> A.{\"你好呀！\":\"hello！！！今天心情很不错哟！\"}  \n",
    "* 4.回复value的信息  \n",
    "* 5.接语音合成，完成智能语音对话机器人"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "45a3b522",
   "metadata": {},
   "outputs": [],
   "source": [
    "qa = {\n",
    "    \"你好\":\"哈喽\",\n",
    "    \"你叫什么\":\"小度\",\n",
    "    \"潘周聃\":\"29岁 硕士毕业于苏黎世联邦理工大学\",\n",
    "    \"听我说\":\"谢谢你，因为有你，温暖了四季\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "13e8b5cc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'哈喽'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qa.get(\"你好\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "497faa12",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'小度'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qa.get(\"你叫什么\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a60fe3a9",
   "metadata": {},
   "source": [
    "* 调用电脑麦克风，将语音转换音频文件\n",
    "* 音频文件--> 调用百度ASR接口"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "54bd0218",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "import speech_recognition\n",
    "\n",
    "r = speech_recognition.Recognizer()\n",
    "\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ca624be4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Package                            Version\n",
      "---------------------------------- -------------------\n",
      "alabaster                          0.7.12\n",
      "anaconda-client                    1.7.2\n",
      "anaconda-navigator                 2.0.3\n",
      "anaconda-project                   0.9.1\n",
      "anyio                              2.2.0\n",
      "appdirs                            1.4.4\n",
      "argh                               0.26.2\n",
      "argon2-cffi                        20.1.0\n",
      "asn1crypto                         1.4.0\n",
      "astroid                            2.5\n",
      "astropy                            4.2.1\n",
      "async-generator                    1.10\n",
      "atomicwrites                       1.4.0\n",
      "attrs                              20.3.0\n",
      "autopep8                           1.5.6\n",
      "Babel                              2.9.0\n",
      "backcall                           0.2.0\n",
      "backports.functools-lru-cache      1.6.4\n",
      "backports.shutil-get-terminal-size 1.0.0\n",
      "backports.tempfile                 1.0\n",
      "backports.weakref                  1.0.post1\n",
      "backports.zoneinfo                 0.2.1\n",
      "bcrypt                             3.2.0\n",
      "beautifulsoup4                     4.9.3\n",
      "bitarray                           1.9.2\n",
      "bkcharts                           0.2\n",
      "black                              19.10b0\n",
      "bleach                             3.3.0\n",
      "bokeh                              2.3.2\n",
      "boto                               2.49.0\n",
      "Bottleneck                         1.3.2\n",
      "brotlipy                           0.7.0\n",
      "certifi                            2020.12.5\n",
      "cffi                               1.14.5\n",
      "chardet                            4.0.0\n",
      "click                              7.1.2\n",
      "cloudpickle                        1.6.0\n",
      "clyent                             1.2.2\n",
      "colorama                           0.4.4\n",
      "comtypes                           1.1.9\n",
      "conda                              4.10.1\n",
      "conda-build                        3.21.4\n",
      "conda-content-trust                0+unknown\n",
      "conda-package-handling             1.7.3\n",
      "conda-repo-cli                     1.0.4\n",
      "conda-token                        0.3.0\n",
      "conda-verify                       3.4.2\n",
      "contextlib2                        0.6.0.post1\n",
      "cryptography                       3.4.7\n",
      "cycler                             0.10.0\n",
      "Cython                             0.29.23\n",
      "cytoolz                            0.11.0\n",
      "dask                               2021.4.0\n",
      "decorator                          5.0.6\n",
      "defusedxml                         0.7.1\n",
      "diff-match-patch                   20200713\n",
      "distributed                        2021.4.0\n",
      "docopt                             0.6.2\n",
      "docutils                           0.17\n",
      "entrypoints                        0.3\n",
      "et-xmlfile                         1.0.1\n",
      "fastcache                          1.1.0\n",
      "filelock                           3.0.12\n",
      "flake8                             3.9.0\n",
      "Flask                              1.1.2\n",
      "fsspec                             0.9.0\n",
      "future                             0.18.2\n",
      "gevent                             21.1.2\n",
      "glob2                              0.7\n",
      "greenlet                           1.0.0\n",
      "h5py                               2.10.0\n",
      "HeapDict                           1.0.1\n",
      "html5lib                           1.1\n",
      "idna                               2.10\n",
      "imagecodecs                        2021.3.31\n",
      "imageio                            2.9.0\n",
      "imagesize                          1.2.0\n",
      "importlib-metadata                 3.10.0\n",
      "iniconfig                          1.1.1\n",
      "intervaltree                       3.1.0\n",
      "ipykernel                          5.3.4\n",
      "ipython                            7.22.0\n",
      "ipython-genutils                   0.2.0\n",
      "ipywidgets                         7.6.3\n",
      "isort                              5.8.0\n",
      "itsdangerous                       1.1.0\n",
      "jdcal                              1.4.1\n",
      "jedi                               0.17.2\n",
      "Jinja2                             2.11.3\n",
      "joblib                             1.0.1\n",
      "Js2Py                              0.71\n",
      "json5                              0.9.5\n",
      "jsonschema                         3.2.0\n",
      "jupyter                            1.0.0\n",
      "jupyter-client                     6.1.12\n",
      "jupyter-console                    6.4.0\n",
      "jupyter-contrib-core               0.3.3\n",
      "jupyter-core                       4.7.1\n",
      "jupyter-nbextensions-configurator  0.4.1\n",
      "jupyter-packaging                  0.7.12\n",
      "jupyter-server                     1.4.1\n",
      "jupyterlab                         3.0.14\n",
      "jupyterlab-pygments                0.1.2\n",
      "jupyterlab-server                  2.4.0\n",
      "jupyterlab-widgets                 1.0.0\n",
      "keyring                            22.3.0\n",
      "kiwisolver                         1.3.1\n",
      "lazy-object-proxy                  1.6.0\n",
      "libarchive-c                       2.9\n",
      "llvmlite                           0.36.0\n",
      "locket                             0.2.1\n",
      "lxml                               4.6.3\n",
      "MarkupSafe                         1.1.1\n",
      "matplotlib                         3.3.4\n",
      "mccabe                             0.6.1\n",
      "menuinst                           1.4.16\n",
      "mistune                            0.8.4\n",
      "mkl-fft                            1.3.0\n",
      "mkl-random                         1.2.1\n",
      "mkl-service                        2.3.0\n",
      "mock                               4.0.3\n",
      "more-itertools                     8.7.0\n",
      "mpmath                             1.2.1\n",
      "msgpack                            1.0.2\n",
      "multipledispatch                   0.6.0\n",
      "mypy-extensions                    0.4.3\n",
      "navigator-updater                  0.2.1\n",
      "nbclassic                          0.2.6\n",
      "nbclient                           0.5.3\n",
      "nbconvert                          6.0.7\n",
      "nbformat                           5.1.3\n",
      "nest-asyncio                       1.5.1\n",
      "networkx                           2.5\n",
      "nltk                               3.6.1\n",
      "nose                               1.3.7\n",
      "notebook                           6.3.0\n",
      "numba                              0.53.1\n",
      "numexpr                            2.7.3\n",
      "numpy                              1.20.1\n",
      "numpydoc                           1.1.0\n",
      "olefile                            0.46\n",
      "openpyxl                           3.0.7\n",
      "packaging                          20.9\n",
      "pandas                             1.2.4\n",
      "pandocfilters                      1.4.3\n",
      "paramiko                           2.7.2\n",
      "parso                              0.7.0\n",
      "partd                              1.2.0\n",
      "path                               15.1.2\n",
      "pathlib2                           2.3.5\n",
      "pathspec                           0.7.0\n",
      "patsy                              0.5.1\n",
      "pep8                               1.7.1\n",
      "pexpect                            4.8.0\n",
      "pickleshare                        0.7.5\n",
      "Pillow                             8.2.0\n",
      "pip                                21.0.1\n",
      "pipwin                             0.5.2\n",
      "pkginfo                            1.7.0\n",
      "pluggy                             0.13.1\n",
      "ply                                3.11\n",
      "prometheus-client                  0.10.1\n",
      "prompt-toolkit                     3.0.17\n",
      "psutil                             5.8.0\n",
      "ptyprocess                         0.7.0\n",
      "py                                 1.10.0\n",
      "PyAudio                            0.2.11\n",
      "pycodestyle                        2.6.0\n",
      "pycosat                            0.6.3\n",
      "pycparser                          2.20\n",
      "pycurl                             7.43.0.6\n",
      "pydocstyle                         6.0.0\n",
      "pyerfa                             1.7.3\n",
      "pyflakes                           2.2.0\n",
      "Pygments                           2.8.1\n",
      "pyjsparser                         2.7.1\n",
      "pylint                             2.7.4\n",
      "pyls-black                         0.4.6\n",
      "pyls-spyder                        0.3.2\n",
      "PyNaCl                             1.4.0\n",
      "pyodbc                             4.0.0-unsupported\n",
      "pyOpenSSL                          20.0.1\n",
      "pyparsing                          2.4.7\n",
      "PyPrind                            2.11.3\n",
      "pyreadline                         2.1\n",
      "pyrsistent                         0.17.3\n",
      "pySmartDL                          1.3.4\n",
      "PySocks                            1.7.1\n",
      "pytest                             6.2.3\n",
      "python-dateutil                    2.8.1\n",
      "python-jsonrpc-server              0.4.0\n",
      "python-language-server             0.36.2\n",
      "pytz                               2021.1\n",
      "pytz-deprecation-shim              0.1.0.post0\n",
      "PyWavelets                         1.1.1\n",
      "pywin32                            227\n",
      "pywin32-ctypes                     0.2.0\n",
      "pywinpty                           0.5.7\n",
      "PyYAML                             5.4.1\n",
      "pyzmq                              20.0.0\n",
      "QDarkStyle                         2.8.1\n",
      "QtAwesome                          1.0.2\n",
      "qtconsole                          5.0.3\n",
      "QtPy                               1.9.0\n",
      "regex                              2021.4.4\n",
      "requests                           2.25.1\n",
      "rope                               0.18.0\n",
      "Rtree                              0.9.7\n",
      "ruamel-yaml-conda                  0.15.100\n",
      "scikit-image                       0.18.1\n",
      "scikit-learn                       0.24.1\n",
      "scipy                              1.6.2\n",
      "seaborn                            0.11.1\n",
      "Send2Trash                         1.5.0\n",
      "setuptools                         52.0.0.post20210125\n",
      "simplegeneric                      0.8.1\n",
      "singledispatch                     0.0.0\n",
      "sip                                4.19.13\n",
      "six                                1.15.0\n",
      "sniffio                            1.2.0\n",
      "snowballstemmer                    2.1.0\n",
      "sortedcollections                  2.1.0\n",
      "sortedcontainers                   2.3.0\n",
      "soupsieve                          2.2.1\n",
      "SpeechRecognition                  3.8.1\n",
      "Sphinx                             4.0.1\n",
      "sphinxcontrib-applehelp            1.0.2\n",
      "sphinxcontrib-devhelp              1.0.2\n",
      "sphinxcontrib-htmlhelp             1.0.3\n",
      "sphinxcontrib-jsmath               1.0.1\n",
      "sphinxcontrib-qthelp               1.0.3\n",
      "sphinxcontrib-serializinghtml      1.1.4\n",
      "sphinxcontrib-websupport           1.2.4\n",
      "spyder                             4.2.5\n",
      "spyder-kernels                     1.10.2\n",
      "SQLAlchemy                         1.4.7\n",
      "statsmodels                        0.12.2\n",
      "sympy                              1.8\n",
      "tables                             3.6.1\n",
      "tblib                              1.7.0\n",
      "terminado                          0.9.4\n",
      "testpath                           0.4.4\n",
      "textdistance                       4.2.1\n",
      "threadpoolctl                      2.1.0\n",
      "three-merge                        0.1.1\n",
      "tifffile                           2021.4.8\n",
      "toml                               0.10.2\n",
      "toolz                              0.11.1\n",
      "tornado                            6.1\n",
      "tqdm                               4.59.0\n",
      "traitlets                          5.0.5\n",
      "typed-ast                          1.4.2\n",
      "typing-extensions                  3.7.4.3\n",
      "tzdata                             2022.1\n",
      "tzlocal                            4.2\n",
      "ujson                              4.0.2\n",
      "unicodecsv                         0.14.1\n",
      "urllib3                            1.26.4\n",
      "watchdog                           1.0.2\n",
      "wcwidth                            0.2.5\n",
      "webencodings                       0.5.1\n",
      "Werkzeug                           1.0.1\n",
      "wheel                              0.36.2\n",
      "widgetsnbextension                 3.5.1\n",
      "win-inet-pton                      1.1.0\n",
      "win-unicode-console                0.5\n",
      "wincertstore                       0.2\n",
      "wrapt                              1.12.1\n",
      "xlrd                               2.0.1\n",
      "XlsxWriter                         1.3.8\n",
      "xlwings                            0.23.0\n",
      "xlwt                               1.3.0\n",
      "xmltodict                          0.12.0\n",
      "yapf                               0.31.0\n",
      "zict                               2.0.0\n",
      "zipp                               3.4.1\n",
      "zope.event                         4.5.0\n",
      "zope.interface                     5.3.0\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "0b6164a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting SpeechRecognition\n",
      "  Downloading SpeechRecognition-3.8.1-py2.py3-none-any.whl (32.8 MB)\n",
      "Installing collected packages: SpeechRecognition\n",
      "Successfully installed SpeechRecognition-3.8.1\n"
     ]
    }
   ],
   "source": [
    " !pip install SpeechRecognition "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "cd9b6108",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "谢谢你，因为有你，温暖了四季\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "API_KEY = '7vVrQGv694z3sSwpGGAPdQSk'\n",
    "SECRET_KEY = '2061LwY18Wq1pIObgqBE8qRwT9NtxUmT'\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = '1.wav'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "#测试自训练平台需要打开以下信息， 自训练平台模型上线后，您会看见 第二步：“”获取专属模型参数pid:8001，modelid:1234”，按照这个信息获取 dev_pid=8001，lm_id=1234\n",
    "# DEV_PID = 8001 ;   \n",
    "# LM_ID = 1234 ;\n",
    "\n",
    "# 极速版 打开注释的话请填写自己申请的appkey appSecret ，并在网页中开通极速版（开通后可能会收费）\n",
    "\n",
    "#DEV_PID = 80001\n",
    "#ASR_URL = 'http://vop.baidu.com/pro_api'\n",
    "#SCOPE = 'brain_enhanced_asr'  # 有此scope表示有asr能力，没有请在网页里开通极速版\n",
    "\n",
    "# 忽略scope检查，非常旧的应用可能没有\n",
    "# SCOPE = False\n",
    "\n",
    "\n",
    "# 极速版\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    # print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "   # print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    " #       print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "# 语音识别接口调用\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "\n",
    "    \"\"\"\n",
    "    httpHandler = urllib2.HTTPHandler(debuglevel=1)\n",
    "    opener = urllib2.build_opener(httpHandler)\n",
    "    urllib2.install_opener(opener)\n",
    "    \"\"\"\n",
    "    speech_data = []\n",
    "    # 打开目标语音文件\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    #测试自训练平台需要打开以下信息\n",
    "    #params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "    params_query = urlencode(params);\n",
    "\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = ASR_URL + \"?\" + params_query\n",
    "#    print(\"url is\", url);\n",
    " #   print(\"header is\", headers)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "    # 异常处理，避免出现红色bug（提前预判可能出现的异常）\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "#        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))   \n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')  # result_str 已经是字符串（字典）\n",
    "  #  print(eval(result_str)[\"result\"][0][:-1])  #eavl()将str--> dict\n",
    "    print(qa.get(eval(result_str)[\"result\"][0][:-1]))      \n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7397acea",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
